import { AppDataSource } from '../config/database';
import { Article } from '../entities/Article';
import { User } from '../entities/User';
import { ArticleLike } from '../entities/ArticleLike';

export class ArticleService {
    private static articleServiceInstance: ArticleService;
    private articleRepository = AppDataSource.getRepository(Article);
    private userRepository = AppDataSource.getRepository(User);
    private articleLikeRepository = AppDataSource.getRepository(ArticleLike);

    private constructor() {}

    // 获取ArticleService的单例实例
    public static getInstance(): ArticleService {
        if (!ArticleService.articleServiceInstance) {
            ArticleService.articleServiceInstance = new ArticleService();
        }
        return ArticleService.articleServiceInstance;
    }

    // 创建新文章，验证作者存在性并保存文章信息
    public async createArticle(data: {
        title: string;
        content: string;
        isPublic: boolean;
        authorId: number;
    }): Promise<Article> {
        const user = await this.userRepository.findOne({ where: { id: data.authorId } });
        if (!user) {
            throw new Error('用户不存在');
        }

        const article = this.articleRepository.create({
            title: data.title,
            content: data.content,
            isPublic: data.isPublic,
            author_id: data.authorId,
            status: 1,
            views: 0,
            likes: 0
        });
        return await this.articleRepository.save(article);
    }

    // 根据ID获取文章详情，包括作者信息
    public async getArticleById(id: number): Promise<Article | null> {
        return await this.articleRepository.findOne({
            where: { id, status: 1 },
            relations: ['author']
        });
    }

    // 更新文章信息，仅允许作者修改自己的文章
    public async updateArticle(id: number, data: {
        title?: string;
        content?: string;
        isPublic?: boolean;
        authorId: number;
    }): Promise<Article | null> {
        const article = await this.articleRepository.findOne({
            where: { id, author_id: data.authorId }
        });

        if (!article) {
            return null;
        }

        if (data.title) article.title = data.title;
        if (data.content) article.content = data.content;
        if (data.isPublic !== undefined) article.isPublic = data.isPublic;
        
        return await this.articleRepository.save(article);
    }

    // 删除文章，验证权限并处理相关点赞记录
    public async deleteArticle(id: number, authorId: number): Promise<{ success: boolean; message?: string }> {
        try {
            // 先检查文章是否存在且属于该用户
            const article = await this.articleRepository.findOne({
                where: { id }
            });

            if (!article) {
                return { success: false, message: '文章不存在' };
            }

            if (article.author_id !== authorId) {
                return { success: false, message: '您没有权限删除此文章' };
            }

            // 先删除相关的点赞记录
            await this.articleLikeRepository.delete({ article_id: id });

            // 执行删除文章操作
            const result = await this.articleRepository.delete({
                id,
                author_id: authorId
            });
            
            return { 
                success: result.affected ? result.affected > 0 : false,
                message: result.affected ? '文章删除成功' : '文章删除失败'
            };
        } catch (error) {
            console.error('删除文章出错:', error);
            return { success: false, message: error instanceof Error ? error.message : '删除文章失败' };
        }
    }

    // 获取指定作者的文章列表，支持分页
    public async getArticlesByAuthor(authorId: number, pageNo: number, pageSize: number) {
        const [articles, total] = await this.articleRepository.findAndCount({
            where: { author_id: authorId },
            order: { created_at: 'DESC' },
            skip: (pageNo - 1) * pageSize,
            take: pageSize
        });

        return {
            list: articles,
            total,
            pageNo,
            pageSize,
            totalPages: Math.ceil(total / pageSize)
        };
    }

    // 获取所有公开文章列表，支持分页
    public async getPublicArticles(pageNo: number, pageSize: number) {
        const [articles, total] = await this.articleRepository.findAndCount({
            where: { isPublic: true },
            order: { created_at: 'DESC' },
            skip: (pageNo - 1) * pageSize,
            take: pageSize
        });

        return {
            list: articles,
            total,
            pageNo,
            pageSize,
            totalPages: Math.ceil(total / pageSize)
        };
    }

    // 切换文章的点赞状态，处理点赞和取消点赞逻辑
    public async toggleLike(articleId: number, userId: number, increment: boolean): Promise<{ success: boolean; alreadyLiked?: boolean }> {
        const article = await this.articleRepository.findOne({
            where: { id: articleId }
        });

        if (!article) {
            return { success: false };
        }

        // 检查用户是否已点赞过该文章
        const existingLike = await this.articleLikeRepository.findOne({
            where: {
                article_id: articleId,
                user_id: userId
            }
        });

        if (increment) {
            // 点赞操作
            if (existingLike) {
                // 用户已经点赞过，返回已点赞标记
                return { success: true, alreadyLiked: true };
            }

            // 创建点赞记录
            const articleLike = this.articleLikeRepository.create({
                article_id: articleId,
                user_id: userId
            });
            await this.articleLikeRepository.save(articleLike);

            // 更新文章点赞数
            article.likes += 1;
            await this.articleRepository.save(article);
            return { success: true, alreadyLiked: false };
        } else {
            // 取消点赞操作
            if (!existingLike) {
                // 用户没有点赞过，返回已取消点赞标记
                return { success: true, alreadyLiked: false };
            }

            // 删除点赞记录
            await this.articleLikeRepository.remove(existingLike);

            // 更新文章点赞数
            article.likes = Math.max(0, article.likes - 1);
            await this.articleRepository.save(article);
            return { success: true, alreadyLiked: true };
        }
    }

    // 增加文章的浏览量
    async incrementViewCount(id: number): Promise<void> {
        await this.articleRepository.increment({ id }, 'views', 1);
    }
} 